import json
from django.core.management.base import BaseCommand
from system.models import Menu, MenuMeta, MenuType, MenuStatus

class Command(BaseCommand):
    help = 'Import menu data from a JSON file'

    def handle(self, *args, **options):
        with open(r'sql/menu.json', 'r', encoding='utf-8') as f:
            menu_data = json.load(f)
        Menu.objects.all().delete()
        MenuMeta.objects.all().delete()
        self.import_menus(menu_data)
        self.stdout.write(self.style.SUCCESS('Menu data imported successfully.'))

    def import_menus(self, menu_data):
        menu_dict = {}

        # 第一遍处理：创建菜单和元数据，不设置父子关系
        for item in menu_data['data']:
            self._create_menu_item(item, menu_dict)

        # 第二遍处理：设置父子关系
        for item in menu_data['data']:
            self._set_parent_relationship(item, menu_dict)

    def _create_menu_item(self, item, menu_dict):
        """创建菜单项及其元数据"""
        # 创建元数据
        meta_data = item.get('meta', {})
        meta = MenuMeta.objects.create(
            title=meta_data.get('title', ''),
            icon=meta_data.get('icon', ''),
            order=meta_data.get('order', 0),
            affix_tab=meta_data.get('affixTab', False),
            badge=meta_data.get('badge', ''),
            badge_type=meta_data.get('badgeType', ''),
            badge_variants=meta_data.get('badgeVariants', ''),
            iframe_src=meta_data.get('iframeSrc', ''),
            link=meta_data.get('link', '')
        )

        # 创建菜单
        menu = Menu.objects.create(
            name=item.get('name', ''),
            status=item.get('status', MenuStatus.ENABLED),
            type=item.get('type', MenuType.MENU),
            path=item.get('path', ''),
            component=item.get('component', ''),
            auth_code=item.get('authCode', ''),
            meta=meta
        )

        menu_dict[item['id']] = menu

        # 处理子菜单项
        if 'children' in item:
            for child in item['children']:
                self._create_menu_item(child, menu_dict)

    def _set_parent_relationship(self, item, menu_dict):
        """设置菜单项的父子关系"""
        menu = menu_dict.get(item['id'])
        if not menu:
            return

        # 处理子菜单项的父子关系
        if 'children' in item:
            for child in item['children']:
                child_menu = menu_dict.get(child['id'])
                if child_menu:
                    child_menu.parent = menu
                    child_menu.save()
                    self._set_parent_relationship(child, menu_dict)